<template>
  <div class="oauth_login_box">
    <div class="oauth_form_box">
      <div class="oauth_form_box_login">
        <div class="triangle-topright" @click="handleQrCodeSignIn(!showQrCodeSignIn)">
          <img
            v-if="!showQrCodeSignIn"
            src="https://manager-1254950508.cosgz.myqcloud.com/2024040309447189c3932e0-754c-11ea-882f-93a245acd5f3.png"
          />
          <img
            v-if="showQrCodeSignIn"
            src="https://manager-1254950508.cosgz.myqcloud.com/202404071753623966b2780-78b5-11ea-8ec4-67f044702c4b.png"
          />
        </div>
        <div class="oauth_form">
          <transition name="slide-fade">
            <QrCodeSignIn
              v-if="showQrCodeSignIn"
              class="qr-code-main"
              signInType="wii_oauth2"
              :clientId="$route.query.app_id"
              @onSignInSuccess="handleQrCodeSignInSuccess"
            />
            <div v-else>
              <div v-if="window === window.top">
                <div style="text-align: center">
                  <Avatar :src="clientIcon" :size="70" />
                </div>
                <div style="text-align: center">
                  <span>登陆到</span>
                  <span style="font-weight: bold;">统一认证服务</span>
                </div>
                <div style="text-align: center">
                  <span>以继续访问</span>
                  <span style="font-weight: bold;">{{clientName}}</span>
                </div>
              </div>
              <Tabs value="smsFormRule" @on-click="handleSigninSwitch">
                <TabPane label="密码登陆" name="passwordFormRule">
                  <Form ref="passwordFormRule" :model="formData" :rules="passwordFormRule">
                    <FormItem prop="user" label="用户">
                      <Input type="text" v-model="formData.user" placeholder="请输入email / phone" />
                    </FormItem>
                    <FormItem prop="password" label="密码">
                      <Input type="password" v-model="formData.password" placeholder="请输入密码" />
                    </FormItem>
                  </Form>
                </TabPane>
                <TabPane label="短信登陆" name="smsFormRule">
                  <Form ref="smsFormRule" :model="formData" :rules="smsFormRule">
                    <FormItem prop="phone" label="电话">
                      <Input type="text" v-model="formData.phone" placeholder="请输入电话号码" />
                    </FormItem>
                    <FormItem prop="smsCode" label="验证码">
                      <Input type="text" v-model="formData.smsCode" placeholder="请输入短信验证码">
                        <span slot="append" style="color: #2d8cf0">
                          <Button
                            type="primary"
                            @click="handleSendSms"
                            :disabled="disableSendSms"
                          >{{smsText}}</Button>
                        </span>
                      </Input>
                    </FormItem>
                  </Form>
                </TabPane>
              </Tabs>
              <div class="forget_password">
                <router-link to="/resetPassword">重置密码</router-link>
              </div>
              <Button
                type="primary"
                @click="handleSubmit(signinType)"
                long
                :loading="loginLoading"
              >登陆</Button>
            </div>
          </transition>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  Form,
  FormItem,
  Input,
  Avatar,
  Button,
  Message,
  Tabs,
  TabPane
} from "view-design";
import QrCodeSignIn from "../QrCodeSignIn";
import Uuid from "uuid";
import config from "@/utils/config";
import storage from "@/utils/storage";
import appService from "@/utils/appService";
export default {
  components: {
    Form,
    FormItem,
    Input,
    Avatar,
    Button,
    Tabs,
    TabPane,
    QrCodeSignIn
  },
  data() {
    return {
      showQrCodeSignIn: true,
      window: window,
      loginLoading: false,
      config: config,
      smsText: "发送验证码",
      disableSendSms: false,
      clientName: "unknown",
      clientIcon: config.publicPath + "static/unknown_oauth2_client.svg",
      signinType: "smsFormRule",
      formData: {
        user: null,
        password: null,
        smsCode: null,
        phone: null
      },
      passwordFormRule: {
        user: [
          {
            required: true,
            message: "请输入邮箱或电话号码",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "请输入密码.",
            trigger: "blur"
          },
          {
            type: "string",
            min: 6,
            message: "密码不能低于6位",
            trigger: "blur"
          }
        ]
      },
      smsFormRule: {
        phone: [
          {
            required: true,
            message: "请输入电话号码",
            trigger: "blur"
          }
        ],
        smsCode: [
          {
            required: true,
            message: "请输入短信验证码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  async beforeMount() {
    let query = this.$route.query;
    let clientId = query.app_id;
    if (clientId) {
      let resposne = await appService.getRequest(
        `${config.serverProxy}${config.authServicePath}/application/getBaseInfo`,
        { clientId: clientId }
      );
      if (resposne.status === 200 && resposne.data.errorCode === 0) {
        this.clientName = resposne.data.data.name;
        if (resposne.data.data.iconUrl) {
          this.clientIcon = resposne.data.data.iconUrl;
        }
      }
    }
  },
  methods: {
    handleQrCodeSignInSuccess(data) {
      let query = this.$route.query;
      let redirect_uri = this.getRedirectUri();
      let slipt = "?";
      if (redirect_uri.indexOf("?") !== -1) {
        slipt = "&";
      }
      let requestUrl = `${redirect_uri}${slipt}auth_code=${data.oauth2Code}&state=${query.state}`;
      let cookies = data.wiiCookies;
      console.log("cookies:" + JSON.stringify(cookies));
      if (cookies) {
        let wiiCookieTimeout = data.wiiCookieTimeout;
        let exdate = new Date(new Date().getTime() + wiiCookieTimeout * 1000);
        for (let cookieName in cookies) {
          storage.setCookie(
            cookieName,
            cookies[cookieName],
            wiiCookieTimeout,
            "ybsjyyn.com"
          );
          console.log("cookie:" + cookieName + "=" + cookies[cookieName]);
        }
      }
      //alert("重定向地址" + requestUrl);
      if (window !== window.top) {
        this.handleIframeEvent(requestUrl);
      } else {
        window.open(requestUrl, "_self");
      }
    },
    handleQrCodeSignIn(show) {
      this.showQrCodeSignIn = show;
    },
    handleIframeEvent(redirect_uri) {
      let message = {
        method: "wiiLoginSuccess",
        url: redirect_uri
      };
      window.top.postMessage(message, "*");
    },
    getRedirectUri() {
      let query = this.$route.query;
      let redirect_uri = query.redirect_uri;
      let indexOf = redirect_uri.indexOf("redirect_uri");
      if (indexOf !== -1) {
        redirect_uri = redirect_uri.substring(
          indexOf + "redirect_uri".length + 1
        );
      }
      redirect_uri = decodeURIComponent(redirect_uri);
      if (redirect_uri.indexOf("?") !== -1) {
        redirect_uri = redirect_uri.substring(0, redirect_uri.indexOf("?"));
      }
      if (redirect_uri.indexOf("&") !== -1) {
        redirect_uri = redirect_uri.substring(0, redirect_uri.indexOf("&"));
      }
      return redirect_uri;
    },
    handleSubmit(rule) {
      let query = this.$route.query;
      if (!query.app_id) {
        Message.error("无效app_id");
        return;
      }
      if (!query.redirect_uri) {
        Message.error("无效redirect_uri");
        return;
      }
      let redirect_uri = this.getRedirectUri();
      // if (redirect_uri.indexOf("#") !== -1) {
      //   redirect_uri = redirect_uri.substring(0, redirect_uri.indexOf("#"));
      // }
      this.$refs[rule].validate(async valid => {
        let vm = this;
        if (valid) {
          vm.loginLoading = true;
          let urlParm = `?app_id=${query.app_id}&scope=${query.scope}`;
          if (query.state) {
            urlParm = urlParm + "&state=" + query.state;
          }
          if (query.response_type) {
            urlParm = urlParm + "&response_type=" + query.response_type;
          }
          let formData = JSON.parse(JSON.stringify(vm.formData));
          if (vm.signinType === "passwordFormRule") {
            var reg = /^\d+$/;
            if (reg.test(formData.user)) {
              formData.phone = formData.user;
            } else {
              formData.email = formData.user;
            }
            delete formData.user;
          } else {
            delete formData.password;
          }
          let resposne = await appService.postRequest(
            `${config.serverProxy}${config.authServicePath}/auth/oauth2/wiiAuthorization${urlParm}`,
            formData
          );
          if (resposne.status === 200 && resposne.data.errorCode === 0) {
            let slipt = "?";
            if (redirect_uri.indexOf("?") !== -1) {
              slipt = "&";
            }
            let requestUrl = `${redirect_uri}${slipt}auth_code=${resposne.data.data}&state=${query.state}`;
            //alert("重定向地址" + requestUrl);
            if (window !== window.top) {
              vm.handleIframeEvent(requestUrl);
            } else {
              window.open(requestUrl, "_self");
            }
          } else {
            vm.loginLoading = false;
          }
        }
      });
    },
    handleSigninSwitch(name) {
      if (name === "passwordFormRule") {
        this.formData.smsCode = null;
        this.formData.phone = null;
        this.signinType = "passwordFormRule";
      } else if (name === "smsFormRule") {
        this.formData.user = null;
        this.formData.password = null;
        this.signinType = "smsFormRule";
      }
    },
    async handleSendSms() {
      let formData = this.formData;
      if (!formData.phone) {
        Message.error("请填写号码");
      } else {
        let resposne = await appService.getRequest(
          `${config.serverProxy}${config.authServicePath}/sms/getLoginCode`,
          { phone: formData.phone }
        );
        if (resposne.data.errorCode === 0) {
          this.disableSendSms = true;
          let countdown = 60;
          let point = window.setInterval(() => {
            if (countdown == 0) {
              this.disableSendSms = false;
              this.smsText = "发送验证码";
              window.clearInterval(point);
            } else {
              this.smsText = countdown + "s";
              countdown = countdown - 1;
            }
          }, 1000);
        }
      }
    }
  }
};
</script>
<style lang="less" scoped>
.oauth_login_box {
  background: #ffffff;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.tengyun_logo_box {
  display: flex;
  justify-content: center;
  padding: 40px;
}
.oauth_form_box {
  display: flex;
  justify-content: center;
  border: 1px solid #f9f9f9;
}
.oauth_form {
  width: 320px;
  background: #ffffff;
  padding: 20px;
}
.forget_password {
  color: #999;
  text-align: right;
}
.oauth_form_box_login {
  position: sticky;
  .triangle-topright {
    width: 40px;
    height: 40px;
    position: absolute;
    right: 0px;
    top: 0px;
    z-index: 2;
    &::after {
      content: "";
      display: block;
      width: 0;
      height: 0;
      border-bottom: 40px solid #ffffff;
      border-right: 40px solid transparent;
      position: absolute;
      left: 0;
      top: 0;
    }
    & > img {
      width: 40px;
      height: 40px;
      position: relative;
    }
  }
  .oauth_form {
    background: #ffffff;
    padding: 20px;
    min-height: 380px;
    .qr-code-main {
      position: absolute;
      top: 0;
      left: 0;
    }
    .forget_password {
      color: #999;
      text-align: right;
    }
  }
}
.slide-fade-enter-active {
  transition: all 0.3s ease;
}
.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}
.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateX(100%);
  opacity: 0;
}
</style>
